/**
 * 提交/删除评论 路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var commentTool = require('../bin/comment');
var userTool = require('../bin/user');
var articleMarkTool = require('../bin/articleMark');
var articleTool = require('../bin/article');
var datetimeTool = require('../bin/util/datetime');
var htmlcheck = require('../bin/htmlcheck');

router.post('/comment', async function(req, res) {

    // 有三种操作：
    // 1.获取文章评论点赞列表, 仅有 article_id
    // 2.进行评论, 并获取评论后的评论点赞列表, 有article_id, basepath, brief
    // 3.删除评论, 并获取删除后的评论点赞列表, 有article_id, basepath, brief, 且 brief === '{[DELETE]}'

    let assert = assertAlljs(req, res, 'json');

    if (await assert(typeof(req.body.article_id) !== 'string', '缺少请求参数'))
        return;

    let article_replys = -1;
    let fonds = [];
    if (typeof(req.body.basepath) === 'string' && typeof(req.body.brief) === 'string'){ // 如果是提交/删除评论
        if (await assert(userTool.check(req.session.user))) // 检查是否登录
            return;

        let {comment, filter, error} = commentTool.fromBody(req.body);
        if (await assert(error))
            return;

        let plus = req.body.brief === '{[REMOVE]}' ? -1 : 1; // -1 则删除，+1 则添加
        if (plus>0){
            if (await assert(htmlcheck.checkComment(comment.brief)))
                return;

            // 查询同路路径下已有的评论，获得当前评论的路径
            let docs = await dbentityTool.find('comment', filter);
            if (await assert(docs instanceof Error, '数据库查询异常'))
                return;
            let comment_idx = 0;
            if (docs.length > 0){
                let startsub = comment.basepath.length + 1;
                let comment_idxs = docs.map((doc) => parseInt(doc.path.substr(startsub)));
                comment_idxs.forEach((idx) => { if (idx > comment_idx) comment_idx = idx; });
                comment_idx++;
            }
            comment.path = comment.basepath + '/' + comment_idx;
            delete comment.basepath;

            // 补充细节信息并上传
            commentTool.newDetails(comment, req.session.user);
            let comment_id = await dbentityTool.upsert('comment', comment);
            if (!(comment_id instanceof Error))
                comment._id = comment_id;
        } else {
            comment.path = comment.basepath;
            delete comment.basepath;

            // 如果是 管理员，文章发布者，评论发布者 允许删除
            let invalidUser = true;
            if (req.session.user.role === 'admin' || req.session.user.role === 'admin:'+res.locals.blockRoot){
                invalidUser = false;
            }else{
                let doc = await dbentityTool.findOne('comment', {article_id:comment.article_id, path:comment.path});
                if (doc.produceUser._id === req.session.user._id){
                    invalidUser = false;
                }else{
                    let doc2 = await dbentityTool.findOne('article', {_id:ObjectID(comment.article_id)});
                    if (doc2.produceUser._id === req.session.user._id){
                        invalidUser = false;
                    }
                }
            }
            if (await assert(invalidUser, '没有权限，需为 管理员/文章发布者/评论发布者'))
                return;

            let result = await dbentityTool.deleteMany('comment', {article_id:comment.article_id, path:{ $regex: '^'+comment.path+'(/.*)?$' }});
            if (await assert(result instanceof Error, '数据库删除记录异常'))
                return;

            plus = -result.deletedCount;

            await dbentityTool.deleteMany('fond', {article_id:comment.article_id, path:{ $regex: '^'+comment.path+'(/.*)?$' }});
        }

        // 更新文章评论数，更新所属评论的评论数
        let result = await articleMarkTool.handleReply(comment.article_id, comment.path, plus);
        let article = result.value;
        article_replys = article.replys;

        //提交给审核页面
        if (plus>0){
            let audit = {
                produceUser: comment.produceUser,
                produceTime: datetimeTool.to_yMdHms(comment.produceTime, '-', ' ', ':'),
                produceArticle: articleTool.getProfile(article),
                type: 'comment',
                path: comment.path,
                brief: comment.brief
            };

            //提交给审核页面
            require('../appWS').io.to('publishaudit').emit('newitem', audit);
        }
    }

    // 获取当前页面的评论
    let docs2 = await dbentityTool.find('comment', {article_id:req.body.article_id});
    docs2.forEach((doc) => { doc.produceTime=datetimeTool.to_yMdHms(doc.produceTime);});

    // 获取当前用户，当前页面的点赞列表
    if (req.session.user != null){
        let docs3 = await dbentityTool.find('fond', {article_id:req.body.article_id, user_id:req.session.user._id});
        fonds = docs3.map((doc)=>doc.path);
    }

    res.json({success:true, article_replys, fonds, comments:docs2});
});

module.exports = router;